<template>
  <div class="pyq-page">
    <!-- Toast 提示组件 -->
    <Toast ref="toastRef" />
    
    <!-- 加载蒙层 -->
    <LoadingOverlay 
      :visible="isLoading"
      :message="loadingMessage"
    />
    
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>朋友圈数据</h2>
      <div class="page-controls">
        <!-- 状态筛选 -->
        <div class="filter-section">
          <label for="status-filter" class="filter-label">状态筛选：</label>
          <select 
            id="status-filter"
            v-model="statusFilter" 
            @change="handleStatusFilterChange"
            class="status-select"
          >
            <option value="">全部</option>
            <option value="0">未审核</option>
            <option value="1">已采用</option>
            <option value="2">未采用</option>
          </select>
        </div>
        <div class="page-info">
          <span class="total-count">共 {{ total }} 条数据</span>
          <span class="current-page">第 {{ currentPage }} 页</span>
        </div>
      </div>
    </div>

    <!-- 数据列表 -->
    <div class="pyq-list">
      <div 
        v-for="item in pyqData" 
        :key="item.id"
        class="pyq-item"
      >
        <!-- 用户信息 -->
        <div class="user-info">
          <div class="user-name">{{ item.user_name || '匿名用户' }}</div>
          <div class="user-estates" v-if="item.user_estates && item.user_estates.length > 0">
            <span class="estate-tag" v-for="estate in item.user_estates" :key="estate">
              {{ estate }}
            </span>
          </div>
          <div class="create-time">{{ formatTime(item.create_time) }}</div>
        </div>

        <!-- 内容 -->
        <div class="content-section">
          <div class="content-text">{{ item.content }}</div>
          
          <!-- 图片展示 -->
          <div class="image-section" v-if="item.urls && getValidImageUrls(item.urls).length > 0">
            <div class="image-grid" :class="getImageGridClass(getValidImageUrls(item.urls).length)">
              <div 
                v-for="(url, index) in getValidImageUrls(item.urls)" 
                :key="index"
                class="image-item"
                @click="previewImage(url, getValidImageUrls(item.urls))"
              >
                <img 
                  :src="getProxyImageUrl(url)" 
                  :alt="`图片${index + 1}`"
                  :data-original-url="url"
                  @error="handleImageError"
                  @load="handleImageLoad"
                  @click="previewImage(url, getValidImageUrls(item.urls))"
                />

                <div class="image-error-overlay" v-if="imageErrors.has(getProxyImageUrl(url))">
                  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
                    <circle cx="8.5" cy="8.5" r="1.5"></circle>
                    <polyline points="21,15 16,10 5,21"></polyline>
                  </svg>
                  <span>图片加载失败</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 底部信息 -->
        <div class="item-footer">
          <div class="type-tag">{{ item.type }}</div>
          <div class="status-tag" :class="getStatusClass(item.has_use)">
            {{ getStatusText(item.has_use) }}
          </div>
          <!-- 操作按钮 -->
          <div class="action-buttons">
            <!-- 链接按钮 -->
            <button 
              v-if="item.url"
              @click="openLink(item.url)" 
              class="action-btn link-btn"
              title="打开链接"
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path>
                <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path>
              </svg>
              原文链接
            </button>
            <!-- 原图按钮 -->
            <button 
              v-if="item.urls && getValidImageUrls(item.urls).length > 0"
              @click="showOriginalImages(item.urls)" 
              class="action-btn original-btn"
              title="查看原图链接"
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
                <circle cx="8.5" cy="8.5" r="1.5"></circle>
                <polyline points="21,15 16,10 5,21"></polyline>
              </svg>
              原图
            </button>
            <!-- 审核按钮 -->
            <div v-if="item.has_use === 0" class="audit-buttons">
              <button 
                @click="updateStatus(item.id, 1)" 
                class="action-btn approve-btn"
                :disabled="item.updating"
              >
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <polyline points="20,6 9,17 4,12"></polyline>
                </svg>
                采用
              </button>
              <button 
                @click="updateStatus(item.id, 2)" 
                class="action-btn reject-btn"
                :disabled="item.updating"
              >
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <line x1="18" y1="6" x2="6" y2="18"></line>
                  <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
                不采用
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页器 -->
    <div class="pagination">
      <button 
        @click="prevPage" 
        :disabled="currentPage <= 1"
        class="page-btn prev-btn"
      >
        上一页
      </button>
      
      <div class="page-numbers">
        <button 
          v-for="pageNum in visiblePages" 
          :key="pageNum"
          @click="goToPage(pageNum)"
          :class="{ active: pageNum === currentPage }"
          class="page-number"
        >
          {{ pageNum }}
        </button>
      </div>
      
      <button 
        @click="nextPage" 
        :disabled="currentPage >= totalPages"
        class="page-btn next-btn"
      >
        下一页
      </button>
    </div>
    
    <!-- 图片预览弹窗 -->
    <div v-if="showImagePreview" class="image-preview-modal" @click="closeImagePreview">
      <div class="preview-content" @click.stop>
        <button class="close-btn" @click="closeImagePreview">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <line x1="18" y1="6" x2="6" y2="18"></line>
            <line x1="6" y1="6" x2="18" y2="18"></line>
          </svg>
        </button>
        <div class="preview-image-container">
          <img :src="previewImageUrl" :alt="`预览图片${previewCurrentIndex + 1}`" :data-original-url="previewImageUrl" />
        </div>
        <div class="preview-nav" v-if="previewImages.length > 1">
          <button @click="prevPreviewImage" class="nav-btn prev">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <polyline points="15,18 9,12 15,6"></polyline>
            </svg>
          </button>
          <span class="preview-counter">{{ previewCurrentIndex + 1 }} / {{ previewImages.length }}</span>
          <button @click="nextPreviewImage" class="nav-btn next">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <polyline points="9,18 15,12 9,6"></polyline>
            </svg>
          </button>
        </div>
      </div>
    </div>

    <!-- 原图链接弹窗 -->
    <div v-if="showOriginalModal" class="original-modal-overlay" @click="closeOriginalModal">
      <div class="original-modal-content" @click.stop>
        <div class="original-modal-header">
          <h3>🖼️ 原图链接</h3>
          <button @click="closeOriginalModal" class="original-modal-close">×</button>
        </div>
        <div class="original-modal-body">
          <div class="original-links-container">
            <div 
              v-for="(url, index) in originalImageUrls" 
              :key="index"
              class="original-link-item"
            >
              <div class="link-content">
                <span class="link-number">图片 {{ index + 1 }}</span>
                <div class="link-url">{{ url }}</div>
              </div>
              <button 
                @click="copyToClipboard(url)" 
                class="copy-btn"
                :title="copyStatus[index] || '复制链接'"
              >
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
                  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
                </svg>
              </button>
            </div>
          </div>
        </div>
        <div class="original-modal-footer">
          <button @click="closeOriginalModal" class="original-modal-btn">关闭</button>
        </div>
      </div>
    </div>

    <!-- 采用弹窗 -->
    <div v-if="showAdoptModal" class="adopt-modal-overlay" @click="closeAdoptModal">
      <div class="adopt-modal-content" @click.stop>
        <div class="adopt-modal-header">
          <h3>📝 采用朋友圈</h3>
          <button @click="closeAdoptModal" class="adopt-modal-close">×</button>
        </div>
        <div class="adopt-modal-body">
          <!-- 楼盘选择 -->
          <div class="adopt-section">
            <h4>🏢 选择楼盘</h4>
            <div class="adopt-estate-search">
              <v-select
                v-model="adoptSelectedEstate"
                :options="adoptEstateOptions"
                :filterable="false"
                @search="onAdoptEstateSearch"
                placeholder="输入关键词搜索楼盘..."
                class="adopt-search-select"
              >
                <template #no-options>
                  <div>输入关键词开始搜索...</div>
                </template>
              </v-select>
            </div>
          </div>

          <!-- 内容编辑 -->
          <div class="adopt-section">
            <h4>💬 内容编辑</h4>
            <textarea
              v-model="adoptContentInput"
              placeholder="请输入内容..."
              class="adopt-content-textarea"
              rows="6"
            ></textarea>
          </div>

          <!-- 图片展示和上传 -->
          <div class="adopt-section">
            <h4>🖼️ 图片管理</h4>
            <div class="adopt-images-container">
              <!-- 现有图片展示 -->
              <div v-if="adoptCurrentImages.length > 0" class="adopt-images-grid">
                <div 
                  v-for="(image, index) in adoptCurrentImages" 
                  :key="index"
                  class="adopt-image-item"
                >
                  <img :src="image" alt="图片" class="adopt-image" />
                  <button @click="removeAdoptImage(index)" class="adopt-image-remove">×</button>
                </div>
              </div>
              
              <!-- 添加图片按钮 -->
              <div class="adopt-image-upload" @click="triggerAdoptFileInput">
                <div class="adopt-upload-placeholder">
                  <div class="adopt-upload-icon">📷</div>
                  <div class="adopt-upload-text">添加图片</div>
                </div>
              </div>
            </div>
            <input
              ref="adoptFileInput"
              type="file"
              accept="image/*"
              multiple
              @change="handleAdoptImageUpload"
              style="display: none"
            />
          </div>
        </div>
        <div class="adopt-modal-footer">
          <button @click="closeAdoptModal" class="adopt-modal-btn cancel-btn">取消</button>
          <button @click="confirmAdoptUpload" class="adopt-modal-btn confirm-btn" :disabled="!canAdoptUpload">
            确认采用
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { getPyqData, getProxyImageUrl } from '../api/pyqAPI.js';
import LoadingOverlay from './LoadingOverlay.vue';
import Toast from './Toast.vue';
import vSelect from 'vue-select';
import axios from 'axios';
import OSS from 'ali-oss';

// 响应式数据
const pyqData = ref([]);
const currentPage = ref(1);
const pageSize = ref(12);
const total = ref(0);
const isLoading = ref(false);
const loadingMessage = ref('加载中...');
const imageErrors = ref(new Set());
const statusFilter = ref('');

// 图片预览相关
const showImagePreview = ref(false);
const previewImageUrl = ref('');
const previewImages = ref([]);
const previewCurrentIndex = ref(0);

// 原图弹窗相关
const showOriginalModal = ref(false);
const originalImageUrls = ref([]);
const copyStatus = ref({});

// 采用弹窗相关
const showAdoptModal = ref(false);
const adoptSelectedEstate = ref(null);
const adoptEstateOptions = ref([]);
const adoptContentInput = ref('');
const adoptCurrentImages = ref([]);
const adoptFileInput = ref(null);
const currentAdoptItem = ref(null);
const adoptImageUploading = ref(false);

// Toast 组件引用
const toastRef = ref(null);

// OSS配置
let ossClient = null;
let ossParams = null;

// 计算属性
const totalPages = computed(() => Math.ceil(total.value / pageSize.value));

const visiblePages = computed(() => {
  const pages = [];
  const start = Math.max(1, currentPage.value - 2);
  const end = Math.min(totalPages.value, currentPage.value + 2);
  
  for (let i = start; i <= end; i++) {
    pages.push(i);
  }
  return pages;
});

// 方法
const loadData = async () => {
  try {
    isLoading.value = true;
    loadingMessage.value = '加载朋友圈数据中...';
    
    const response = await getPyqData(currentPage.value, pageSize.value, statusFilter.value);
    
    if (response.success) {
      pyqData.value = response.data;
      total.value = response.total;
    } else {
      console.error('获取数据失败:', response.message);
    }
  } catch (error) {
    console.error('加载数据失败:', error);
  } finally {
    isLoading.value = false;
  }
};

const handleStatusFilterChange = () => {
  // 重置到第一页
  currentPage.value = 1;
  // 重新加载数据
  loadData();
};

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    loadData();
  }
};

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
    loadData();
  }
};

const goToPage = (page) => {
  currentPage.value = page;
  loadData();
};

const formatTime = (timeStr) => {
  if (!timeStr) return '';
  const date = new Date(timeStr);
  return date.toLocaleString('zh-CN');
};

const getImageGridClass = (count) => {
  if (count === 1) return 'single';
  if (count === 2) return 'double';
  if (count === 3) return 'triple';
  return 'multiple';
};

const getValidImageUrls = (urls) => {
  if (!urls || !Array.isArray(urls)) return [];
  
  return urls.filter(url => {
    // 微信图片链接
    if (url.includes('qpic.cn') || url.includes('wxapp.tc.qq.com')) {
      return true;
    }
    
    // 其他常见图片格式
    const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'];
    const hasImageExtension = imageExtensions.some(ext => url.toLowerCase().includes(ext));
    
    // 检查是否是图片内容类型
    const isImageContent = url.includes('/image/') || url.includes('image/') || url.includes('img/');
    
    return hasImageExtension || isImageContent;
  });
};

const handleImageError = (event) => {
  const img = event.target;
  const url = img.src;
  
  // 如果当前是代理URL，尝试直接访问原图
  if (url.includes('/proxy/image')) {
    const originalUrl = decodeURIComponent(url.split('url=')[1]);
    if (originalUrl) {
      img.src = originalUrl;
      return;
    }
  }
  
  imageErrors.value.add(url);
  console.warn('图片加载失败:', url);
};

const handleImageLoad = (event) => {
  const img = event.target;
  const url = img.src;
  imageErrors.value.delete(url);
};



const getStatusText = (status) => {
  switch (status) {
    case 0: return '未审核';
    case 1: return '已采用';
    case 2: return '未采用';
    default: return '未知';
  }
};

const getStatusClass = (status) => {
  switch (status) {
    case 0: return 'pending';
    case 1: return 'approved';
    case 2: return 'rejected';
    default: return '';
  }
};

const updateStatus = async (articleId, status) => {
  try {
    // 设置更新状态
    const item = pyqData.value.find(item => item.id === articleId);
    if (item) {
      item.updating = true;
    }
    
    if (status === 1) {
      // 如果是要采用，显示弹窗
      showAdoptModal.value = true;
      currentAdoptItem.value = item;
      adoptContentInput.value = item.content || '';
      adoptCurrentImages.value = item.urls ? getValidImageUrls(item.urls) : [];
      return;
    }
    
    const response = await fetch('/media/article/update/pyq/status', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        article_id: articleId,
        status: status
      })
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    
    if (data.success) {
      // 更新本地状态
      if (item) {
        item.has_use = status;
        item.updating = false;
      }
      console.log('状态更新成功');
      
      // 显示成功提示
      const statusText = status === 1 ? '已采用' : status === 2 ? '未采用' : '未知状态';
      if (toastRef.value) {
        toastRef.value.show(`操作成功！该朋友圈已标记为${statusText}`, 'success', 2000);
      }
    } else {
      console.error('状态更新失败:', data.message);
      if (toastRef.value) {
        toastRef.value.show('状态更新失败，请重试', 'error', 3000);
      }
    }
  } catch (error) {
    console.error('更新状态失败:', error);
  } finally {
    // 清除更新状态
    const item = pyqData.value.find(item => item.id === articleId);
    if (item) {
      item.updating = false;
    }
  }
};

const previewImage = (url, images) => {
  // 如果图片加载失败，不进行预览
  // if (imageErrors.value.has(getProxyImageUrl(url))) {
  //   return;
  // }
  
  // 设置预览数据
  previewImages.value = images;
  previewCurrentIndex.value = images.indexOf(url);
  // previewImageUrl.value = getProxyImageUrl(url);
  previewImageUrl.value = url;
  showImagePreview.value = true;
};

const closeImagePreview = () => {
  showImagePreview.value = false;
};

const prevPreviewImage = () => {
  if (previewCurrentIndex.value > 0) {
    previewCurrentIndex.value--;
    // previewImageUrl.value = getProxyImageUrl(previewImages.value[previewCurrentIndex.value]);
    previewImageUrl.value = previewImages.value[previewCurrentIndex.value];
  }
};

const nextPreviewImage = () => {
  if (previewCurrentIndex.value < previewImages.value.length - 1) {
    previewCurrentIndex.value++;
    // previewImageUrl.value = getProxyImageUrl(previewImages.value[previewCurrentIndex.value]);
    previewImageUrl.value = previewImages.value[previewCurrentIndex.value];
  }
};

// 显示原图链接弹窗
const showOriginalImages = (urls) => {
  originalImageUrls.value = getValidImageUrls(urls);
  showOriginalModal.value = true;
  // 重置复制状态
  copyStatus.value = {};
};

// 关闭原图链接弹窗
const closeOriginalModal = () => {
  showOriginalModal.value = false;
  originalImageUrls.value = [];
  copyStatus.value = {};
};

// 复制到剪贴板
const copyToClipboard = async (text) => {
  try {
    await navigator.clipboard.writeText(text);
    // 设置复制成功状态
    const index = originalImageUrls.value.indexOf(text);
    copyStatus.value[index] = '已复制';
    
    // 2秒后重置状态
    setTimeout(() => {
      copyStatus.value[index] = '';
    }, 2000);
  } catch (err) {
    console.error('复制失败:', err);
    // 降级方案：使用传统方法
    const textArea = document.createElement('textarea');
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.select();
    try {
      document.execCommand('copy');
      const index = originalImageUrls.value.indexOf(text);
      copyStatus.value[index] = '已复制';
      setTimeout(() => {
        copyStatus.value[index] = '';
      }, 2000);
    } catch (fallbackErr) {
      console.error('降级复制也失败:', fallbackErr);
      alert('复制失败，请手动复制');
    }
    document.body.removeChild(textArea);
  }
};

// 打开链接
const openLink = (url) => {
  if (!url) return;
  
  // 检查URL格式
  let targetUrl = url;
  if (!url.startsWith('http://') && !url.startsWith('https://')) {
    targetUrl = 'https://' + url;
  }
  
  // 在新窗口中打开链接
  window.open(targetUrl, '_blank', 'noopener,noreferrer');
};

// 获取OSS上传参数
const getOSSParams = async () => {
  try {
    const response = await axios.get('/api/erp/screenshot/data/oss');
    if (response.data && response.data.data) {
      ossParams = response.data.data;
      console.log('获取OSS参数成功:', ossParams);
      return ossParams;
    } else {
      throw new Error('OSS参数响应格式错误');
    }
  } catch (error) {
    console.error('获取OSS参数失败:', error);
    throw error;
  }
};

// 初始化OSS客户端
const initOSSClient = async () => {
  try {
    if (!ossParams) {
      await getOSSParams();
    }
    
    ossClient = new OSS({
      region: 'oss-cn-hangzhou',
      accessKeyId: ossParams.OSSAccessKeyId,
      accessKeySecret: '8jPhIKCqdJ0DWe0RYiEyFsjIKVlI70',
      internal: false,
      bucket: 'xiaoji-hangzhou',
      timeout: 60000,
      secure: true,
      cname: false,
      retryMax: 3,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type, Authorization'
      }
    });
    console.log('OSS客户端初始化成功');
  } catch (error) {
    console.error('OSS客户端初始化失败:', error);
  }
};

// 楼盘搜索方法
const onAdoptEstateSearch = (search, loading) => {
  if (search.length) {
    loading(true);
    // axios.post('/api/erp/get/searchEstateName', {
      axios.post('/formal/erp/ai/get/searchEstateName', {
      search: search
    })
    .then(response => {
      if (response.data && Array.isArray(response.data.data)) {
        adoptEstateOptions.value = response.data.data.map(item => ({
          label: item.real_estate_name + '(' + item.type + ')',
          id: item.id,
          type: item.type,
          value: item.real_estate_name
        }));
      } else {
        adoptEstateOptions.value = [];
      }
    })
    .catch(error => {
      console.error("楼盘搜索API调用失败:", error);
      adoptEstateOptions.value = [];
    })
    .finally(() => {
      loading(false);
    });
  }
};

// 计算属性
const canAdoptUpload = computed(() => {
  return adoptSelectedEstate.value && adoptContentInput.value.trim();
});

// 关闭采用弹窗
const closeAdoptModal = () => {
  showAdoptModal.value = false;
  currentAdoptItem.value = null;
  adoptSelectedEstate.value = null;
  adoptContentInput.value = '';
  adoptCurrentImages.value = [];
  adoptEstateOptions.value = [];
};

// 触发文件选择
const triggerAdoptFileInput = () => {
  adoptFileInput.value?.click();
};

// 处理图片上传
const handleAdoptImageUpload = async (event) => {
  const files = Array.from(event.target.files);
  if (files.length === 0) return;

  adoptImageUploading.value = true;
  
  try {
    // 初始化OSS客户端
    if (!ossClient) {
      await initOSSClient();
    }

    for (const file of files) {
      // 检查文件类型
      if (!file.type.startsWith('image/')) {
        console.warn('跳过非图片文件:', file.name);
        continue;
      }

      // 检查文件大小 (5MB)
      if (file.size > 5 * 1024 * 1024) {
        console.warn('图片大小超过5MB:', file.name);
        continue;
      }

      // 生成唯一的文件名
      const timestamp = Date.now();
      const randomStr = Math.random().toString(36).substring(2, 8);
      const fileExtension = file.name.split('.').pop();
      const fileName = `img/${timestamp}_${randomStr}.${fileExtension}`;

      try {
        // 使用从接口获取的参数生成预签名URL
        if (!ossParams) {
          await getOSSParams();
        }

        // 构建表单数据
        const formData = new FormData();
        formData.append('key', fileName);
        formData.append('policy', ossParams.policy);
        formData.append('OSSAccessKeyId', ossParams.OSSAccessKeyId);
        formData.append('signature', ossParams.signature);
        formData.append('success_action_status', '200');
        formData.append('file', file);

        // 直接上传到OSS
        const ossUploadResponse = await fetch('https://xiaoji-hangzhou.oss-cn-hangzhou.aliyuncs.com', {
          method: 'POST',
          body: formData
        });

        if (ossUploadResponse.ok) {
          const finalUrl = `https://xiaoji-hangzhou.oss-cn-hangzhou.aliyuncs.com/${fileName}`;
          console.log('OSS上传成功:', finalUrl);
          adoptCurrentImages.value.push(finalUrl);
        } else {
          throw new Error(`OSS上传失败: ${ossUploadResponse.status}`);
        }
      } catch (ossError) {
        console.error('OSS上传失败:', ossError);
        
        // 尝试直接OSS上传
        try {
          const result = await ossClient.put(fileName, file, {
            timeout: 60000,
            headers: {
              'Content-Type': file.type
            }
          });
          
          console.log('直接OSS上传成功:', result.url);
          adoptCurrentImages.value.push(result.url);
        } catch (directError) {
          console.error('直接OSS上传也失败:', directError);
        }
      }
    }
  } catch (error) {
    console.error('图片上传失败:', error);
  } finally {
    adoptImageUploading.value = false;
    // 清空文件输入
    if (adoptFileInput.value) {
      adoptFileInput.value.value = '';
    }
  }
};

// 删除图片
const removeAdoptImage = (index) => {
  adoptCurrentImages.value.splice(index, 1);
};

// 防抖函数
const debounce = (func, delay) => {
  let timeoutId;
  return function (...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(this, args), delay);
  };
};

// 确认采用上传
const confirmAdoptUpload = debounce(async () => {
  if (!canAdoptUpload.value) {
    if (toastRef.value) {
      toastRef.value.show('请选择楼盘并输入内容', 'warning', 2000);
    }
    return;
  }

  try {
    const requestParams = {
      estate_id: adoptSelectedEstate.value.id,
      words: adoptContentInput.value,
      images: adoptCurrentImages.value
    };

    const response = await axios.post('/formal/erp/ai/add/estate/dynamic', requestParams, {
      headers: {
        'Content-Type': 'application/json',
      },
    });

        if (response.data && response.data.success) {
      console.log('采用上传成功');
      
      const response = await fetch('/media/article/update/pyq/status', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
          },
        body: JSON.stringify({
          article_id: currentAdoptItem.value.id,
          status: 1
        })
      });
      
      // 更新本地状态
      if (currentAdoptItem.value) {
        currentAdoptItem.value.has_use = 1;
        currentAdoptItem.value.updating = false;
      }

      // 显示成功提示
      if (toastRef.value) {
        toastRef.value.show('采用上传成功！', 'success', 2000);
      }
      
      // 关闭弹窗
      closeAdoptModal();
    } else {
      console.error('采用上传失败:', response.data);
      if (toastRef.value) {
        toastRef.value.show('上传失败，请重试', 'error', 3000);
      }
    }
  } catch (error) {
    console.error('采用上传出错:', error);
    if (toastRef.value) {
      toastRef.value.show('上传出错，请重试', 'error', 3000);
    }
  }
}, 500); // 500ms 防抖延迟

// 生命周期
onMounted(() => {
  loadData();
  initOSSClient();
});
</script>

<style scoped>
.pyq-page {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  background: #f8f9fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.page-header h2 {
  margin: 0 0 15px 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
}

.page-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.filter-section {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-label {
  font-size: 14px;
  color: #6c757d;
  font-weight: 500;
}

.status-select {
  padding: 8px 12px;
  border: 1px solid #dee2e6;
  border-radius: 6px;
  background: white;
  color: #495057;
  font-size: 14px;
  cursor: pointer;
  transition: border-color 0.2s ease;
}

.status-select:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}



.page-info {
  display: flex;
  gap: 15px;
  font-size: 14px;
  color: #6c757d;
}

.total-count, .current-page {
  padding: 4px 8px;
  background: #e9ecef;
  border-radius: 4px;
}

.pyq-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(450px, 1fr));
  gap: 16px;
}

.pyq-item {
  background: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  height: fit-content;
}

.pyq-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.user-name {
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
}

.user-estates {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.estate-tag {
  padding: 2px 8px;
  background: #e3f2fd;
  color: #1976d2;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.create-time {
  color: #6c757d;
  font-size: 14px;
  margin-left: auto;
}

.content-section {
  margin-bottom: 16px;
}

.content-text {
  font-size: 14px;
  line-height: 1.6;
  color: #2c3e50;
  margin-bottom: 12px;
  word-wrap: break-word;
  white-space: pre-wrap;
}

.image-section {
  margin-top: 12px;
}

.image-grid {
  display: grid;
  gap: 8px;
  border-radius: 8px;
  overflow: hidden;
  justify-content: start;
}

.image-grid.single {
  grid-template-columns: 100px;
  max-width: 100px;
}

.image-grid.double {
  grid-template-columns: 100px 100px;
  max-width: 220px;
  gap: 10px;
}

.image-grid.triple {
  grid-template-columns: 100px 100px 100px;
  max-width: 320px;
  gap: 10px;
}

.image-grid.multiple {
  grid-template-columns: repeat(auto-fit, 100px);
  max-width: 100%;
  gap: 10px;
}

.image-item {
  width: 100px;
  height: 100px;
  overflow: hidden;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.2s ease;
  position: relative;
}

.image-item:hover {
  transform: scale(1.05);
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-loading-overlay,
.image-error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #6c757d;
  font-size: 12px;
  text-align: center;
  border-radius: 8px;
}

.image-loading-overlay svg,
.image-error-overlay svg {
  margin-bottom: 4px;
  opacity: 0.6;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}



.item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #e9ecef;
}

.type-tag, .status-tag {
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 500;
}

.type-tag {
  background: #f3e5f5;
  color: #7b1fa2;
}

.status-tag {
  background: #e8f5e8;
  color: #388e3c;
}

.status-tag.pending {
  background: #fff3e0;
  color: #f57c00;
}

.status-tag.approved {
  background: #e8f5e8;
  color: #388e3c;
}

.status-tag.rejected {
  background: #ffebee;
  color: #d32f2f;
}

.action-buttons {
  display: flex;
  gap: 8px;
  margin-left: auto;
  align-items: center;
}

.audit-buttons {
  display: flex;
  gap: 8px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  border: none;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.action-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.approve-btn {
  background: #4caf50;
  color: white;
}

.approve-btn:hover:not(:disabled) {
  background: #388e3c;
}

.reject-btn {
  background: #f44336;
  color: white;
}

.reject-btn:hover:not(:disabled) {
  background: #d32f2f;
}

.original-btn {
  background: #17a2b8;
  color: white;
}

.original-btn:hover:not(:disabled) {
  background: #138496;
}

.link-btn {
  background: #6f42c1;
  color: white;
}

.link-btn:hover:not(:disabled) {
  background: #5a2d91;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 12px;
  margin-top: 30px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.page-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 10px 16px;
  border: 1px solid #dee2e6;
  background: white;
  color: #495057;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
}

.page-btn:hover:not(:disabled) {
  background: #e9ecef;
  border-color: #adb5bd;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-numbers {
  display: flex;
  gap: 4px;
}

.page-number {
  padding: 10px 14px;
  border: 1px solid #dee2e6;
  background: white;
  color: #495057;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
  min-width: 40px;
}

.page-number:hover {
  background: #e9ecef;
  border-color: #adb5bd;
}

.page-number.active {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

@media (max-width: 768px) {
  .pyq-page {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .pyq-list {
    grid-template-columns: 1fr;
  }
  
  .user-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .create-time {
    margin-left: 0;
  }
  
  .image-grid.double,
  .image-grid.triple {
    grid-template-columns: 1fr;
  }
  
  .pagination {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .page-numbers {
    order: 2;
    width: 100%;
    justify-content: center;
  }
}

/* 图片预览弹窗样式 */
.image-preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.preview-content {
  position: relative;
  max-width: 90vw;
  max-height: 90vh;
  background: white;
  border-radius: 12px;
  overflow: hidden;
}

.close-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  transition: background 0.2s ease;
}

.close-btn:hover {
  background: rgba(0, 0, 0, 0.7);
}

.preview-image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  max-height: 80vh;
}

.preview-image-container img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.preview-nav {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
  gap: 20px;
  background: rgba(0, 0, 0, 0.7);
  padding: 10px 20px;
  border-radius: 25px;
  color: white;
}

.nav-btn {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  padding: 5px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background 0.2s ease;
}

.nav-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.preview-counter {
  font-size: 14px;
  font-weight: 500;
}

/* 采用弹窗样式 */
.adopt-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.adopt-modal-content {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  width: 90%;
  max-width: 600px;
  max-height: 80%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.adopt-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #e9ecef;
  background: #f8f9fa;
}

.adopt-modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #2c3e50;
}

.adopt-modal-close {
  background: none;
  border: none;
  font-size: 24px;
  color: #6c757d;
  cursor: pointer;
  transition: color 0.3s ease;
}

.adopt-modal-close:hover {
  color: #dc3545;
}

.adopt-modal-body {
  padding: 24px;
  flex-grow: 1;
  overflow-y: auto;
}

.adopt-section {
  margin-bottom: 24px;
}

.adopt-section h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #2c3e50;
  font-weight: 600;
}

.adopt-estate-search {
  width: 100%;
}

.adopt-search-select {
  width: 100%;
}

.adopt-content-textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #dee2e6;
  border-radius: 6px;
  font-size: 14px;
  font-family: inherit;
  resize: vertical;
  min-height: 120px;
  transition: border-color 0.3s ease;
}

.adopt-content-textarea:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.adopt-images-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.adopt-images-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.adopt-image-item {
  position: relative;
  width: 100px;
  height: 100px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.adopt-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.adopt-image-remove {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 24px;
  height: 24px;
  border: none;
  border-radius: 50%;
  background: rgba(220, 53, 69, 0.9);
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  transition: background 0.3s ease;
}

.adopt-image-remove:hover {
  background: rgba(220, 53, 69, 1);
}

.adopt-image-upload {
  width: 100px;
  height: 100px;
  cursor: pointer;
}

.adopt-upload-placeholder {
  width: 100%;
  height: 100%;
  border: 2px dashed #dee2e6;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  transition: all 0.3s ease;
  background: #f8f9fa;
}

.adopt-upload-placeholder:hover {
  border-color: #007bff;
  background: rgba(0, 123, 255, 0.05);
}

.adopt-upload-icon {
  font-size: 24px;
  margin-bottom: 8px;
  color: #6c757d;
}

.adopt-upload-text {
  font-size: 12px;
  color: #6c757d;
  text-align: center;
}

.adopt-modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px;
  border-top: 1px solid #e9ecef;
  background: #f8f9fa;
}

.adopt-modal-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.adopt-modal-btn.cancel-btn {
  background: #e0e0e0;
  color: #495057;
}

.adopt-modal-btn.cancel-btn:hover {
  background: #d0d0d0;
}

.adopt-modal-btn.confirm-btn {
  background: #007bff;
  color: white;
}

.adopt-modal-btn.confirm-btn:hover:not(:disabled) {
  background: #0056b3;
}

.adopt-modal-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* vue-select 样式 */
:deep(.adopt-search-select .vs__dropdown-toggle) {
  padding: 8px 12px;
  border: 1px solid #dee2e6;
  border-radius: 6px;
  background: white;
  transition: border-color 0.3s ease;
  min-height: 36px;
}

:deep(.adopt-search-select .vs__dropdown-toggle:focus) {
  border-color: #007bff;
  outline: none;
}

:deep(.adopt-search-select .vs__search) {
  padding: 0;
  margin: 0;
  border: none;
  background: transparent;
  font-size: 14px;
  color: #495057;
  min-height: 20px;
}

:deep(.adopt-search-select .vs__search::placeholder) {
  color: #6c757d;
}

:deep(.adopt-search-select .vs__dropdown-menu) {
  border: 1px solid #dee2e6;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background: white;
}

:deep(.adopt-search-select .vs__dropdown-option) {
  padding: 8px 12px;
  font-size: 14px;
  color: #495057;
  transition: background-color 0.2s ease;
}

:deep(.adopt-search-select .vs__dropdown-option--highlight) {
  background: #007bff;
  color: white;
}

:deep(.adopt-search-select .vs__dropdown-option--selected) {
  background: rgba(0, 123, 255, 0.1);
  color: #007bff;
}

:deep(.adopt-search-select .vs__clear) {
  display: none;
}

:deep(.adopt-search-select .vs__open-indicator) {
  fill: #6c757d;
  transition: transform 0.2s ease;
}

:deep(.adopt-search-select.vs--open .vs__open-indicator) {
  transform: rotate(180deg);
}

:deep(.adopt-search-select.vs--open .vs__dropdown-toggle) {
  border-color: #007bff;
  background-color: #ffffff;
  box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.15);
}

/* 原图弹窗样式 */
.original-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.original-modal-content {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  width: 90%;
  max-width: 800px;
  max-height: 80%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.original-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #e9ecef;
  background: #f8f9fa;
}

.original-modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #2c3e50;
}

.original-modal-close {
  background: none;
  border: none;
  font-size: 24px;
  color: #6c757d;
  cursor: pointer;
  transition: color 0.3s ease;
}

.original-modal-close:hover {
  color: #dc3545;
}

.original-modal-body {
  padding: 24px;
  flex-grow: 1;
  overflow-y: auto;
}

.original-links-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.original-link-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  position: relative;
}

.link-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.link-number {
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
}

.link-url {
  font-family: 'Courier New', monospace;
  font-size: 12px;
  color: #495057;
  background: white;
  padding: 8px 12px;
  border-radius: 4px;
  border: 1px solid #dee2e6;
  word-break: break-all;
  line-height: 1.4;
  max-height: 60px;
  overflow-y: auto;
}

.copy-btn {
  background: #007bff;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 36px;
  height: 36px;
  flex-shrink: 0;
}

.copy-btn:hover {
  background: #0056b3;
  transform: translateY(-1px);
}

.copy-btn:active {
  transform: translateY(0);
}

.original-modal-footer {
  display: flex;
  justify-content: flex-end;
  padding: 16px 24px;
  border-top: 1px solid #e9ecef;
  background: #f8f9fa;
}

.original-modal-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #6c757d;
  color: white;
}

.original-modal-btn:hover {
  background: #545b62;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .original-modal-content {
    width: 95%;
    max-height: 90%;
  }
  
  .original-modal-body {
    padding: 16px;
  }
  
  .original-link-item {
    flex-direction: column;
    gap: 8px;
  }
  
  .copy-btn {
    align-self: flex-end;
  }
}
</style> 